package com.sencorsta.ids.game.world.bean;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.function.FunctionSystem;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.game.db.Wallet;
import com.sencorsta.ids.game.world.game.Game;
import com.sencorsta.ids.game.world.room.Room;
import com.sencorsta.utils.random.ICeRandom;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author TAO
 * @description: 世界
 * @date 2019/11/14 20:02
 */
public class World implements RedisService {

    //整个游戏的手续费
    public double serviceCharge = 0.1;

    //系统水线（资金浮动值）--资金参考线
    //public long SYSWATERLINE = 10000;

    public HashMap<String,Long> SYSWATERLINE_ROOM = new HashMap<>();
    public HashMap<String,Long> SYSWATERPOOL_ROOM = new HashMap<>();

    public HashMap<String,Long> SYSKILLRATE_ROOM = new HashMap<>();

    //当前水池
    //public long SYSWATERPOOL;

    //所有机器人的受益+系统抽水

    //所有游戏玩家记录（玩家的userId、所在的房间、玩家类型）
    public Map<String, Player> allPlayers = new ConcurrentHashMap<>();

    public Map<Integer, Game> games = new ConcurrentHashMap<>();

    public final static int SAOLEI = 1;//扫雷
    public final static int NIUNIU = 2;//牛牛
    public final static int JINGQIANG = 3;//禁抢
    public final static int LONGHU = 4;//龙虎
    public final static int WELFARE = 5;//福利
    public final static int JIELONG = 6;//接龙

    public static World instance;

    public static World getInstance() {
        if (instance == null) {
            synchronized (World.class) {
                if (instance == null) {
                    instance = new World();
                    FunctionSystem.addScheduleJob(() -> {
                        try{
                            for (String roomId:instance.SYSWATERLINE_ROOM.keySet()) {
                                instance.SYSWATERLINE_ROOM.put(roomId,R_SYSTEM.getLong(WATERLINE + "-" + roomId));
                            }
                            for (String roomId:instance.SYSWATERPOOL_ROOM.keySet()) {
                                instance.SYSWATERPOOL_ROOM.put(roomId,R_SYSTEM.getLong(WATERPOOL + "-" + roomId));
                            }
                            for (String roomId:instance.SYSKILLRATE_ROOM.keySet()) {
                                instance.SYSKILLRATE_ROOM.put(roomId,R_SYSTEM.getLong(KILLRATE + "-" + roomId));
                            }
                        }catch (Exception e){
                            Out.warn("周期获取配置出错");
                        }
                    }, 3, 3, TimeUnit.SECONDS);
                }
            }
        }
        return instance;
    }


    //lineWater水线 poorW水池
    public boolean isMustWin(long lineWater, long poorW) {
        double lineW = Math.abs(lineWater);
        double temp;
        Random random = new Random();
        if (lineW == 0) {
            temp = 1;
        } else {
            temp = Math.abs(poorW - lineW) / lineW;
        }
        if (poorW > lineW) {//钱
            if (random.nextDouble() < temp) {
                //机器人必输
                return false;
            } else {
                if (random.nextInt(100) < 50) {
                    //机器人必输
                    return false;
                } else {
                    //机器人必赢
                    return true;
                }
            }
        } else {//收钱
            if (random.nextDouble() < temp) {
                //机器人必赢
                return true;
            } else {
                if (random.nextInt(100) < 50) {
                    //机器人必输
                    return false;
                } else {
                    //机器人必赢
                    return true;
                }
            }
        }
    }

    public boolean isMustWinPer(long rate, long bored) {
        if (rate<0)rate=0;
        if (bored<=0)bored=1;
        if (rate>bored)rate=bored;

        return ICeRandom.getDynamic().nextLong(bored)<rate;
    }

//    public boolean isMustWinbyRoom(int roomId) {
//        long line=SYSWATERLINE_ROOM.get(roomId+"");
//        long poor=SYSWATERPOOL_ROOM.get(roomId+"");
//
//        boolean isMustWin=isMustWin(line, poor);
//        Out.trace("roomId:",roomId," 必赢：",isMustWin," line:",line," poor:",poor);
//        return isMustWin;
//    }

    public boolean isMustWinbyRoom(int roomId) {
        long rate=SYSKILLRATE_ROOM.get(roomId+"");
        long bored=100;
        boolean isMustWin= isMustWinPer(rate,bored);
        Out.trace("roomId:",roomId," 必赢：",isMustWin," rate:",rate);
        return isMustWin;
    }


    public void leaveWorld(String userId) {
        Player player = allPlayers.get(userId);
        if (player != null&&player.room!=null) {
            player.room.leave(player);
            if (player.rpSetSize() == 0) {
                allPlayers.remove(userId);
            }
        }
    }

    public void checkUser(String userId) {
        Player player = allPlayers.get(userId);
        if (player != null && player.room == null && player.rpSetSize() == 0) {
            allPlayers.remove(userId);
        }
    }

    public Player enterWorld(String userId, Room room) {
        Player player = allPlayers.get(userId);
        if (player == null) {
            List<String> userInfo = R_USER.hmget(userId, "type", "nickname", "portrait");// 标识机器人、得到发包者昵称、得到发包者头像
            String SID = R_ROUTE.hget(userId, "proxy");

            JSONObject amountAndFreeze = Wallet.getAmountAndFreeze(userId);
            long amount = amountAndFreeze.getLong("amount");
            player = new Player(Integer.valueOf(userInfo.get(0)), userInfo.get(1), userInfo.get(2), userId, SID);
            player.amount = amount;
        }
        if (player.room != null) {
            if (player.room != room) {
                player.room.leave(player);
                room.enter(player);
            }
        } else {
            room.enter(player);
        }
        allPlayers.put(userId,player);
        return player;
    }


//    public static void main(String[] args) {
//        World ww=new World();
//
//        int count=0;
//        int num=10000;
//        for (int i = 0; i < 10000; i++) {
//            if (ww.isMustWinPer(-99,-100))count++;
//        }
//        System.out.println(count+"/"+num);
//    }


}
